package com.juzipi.demo.config;


import com.auth0.jwt.exceptions.TokenExpiredException;
import com.juzipi.demo.tools.Result;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class ExceptionAdvice {


    /**
     * 捕捉所有Shiro异常
     */
    @ExceptionHandler(ShiroException.class)
    public Result handle401(ShiroException e) {
        return Result.fail(401, "无权访问(Unauthorized):" + e.getMessage());
    }



    @ExceptionHandler(UnauthorizedException.class)
    public Result handle401(UnauthorizedException e) {
        Result result = new Result();
        return Result.fail(401, "无权访问(Unauthorized):当前Subject没有此请求所需权限(" + e.getMessage() + ")");
    }


    /**
     * 单独捕捉Shiro(UnauthenticatedException)异常
     * 该异常为以游客身份访问有权限管控的请求无法对匿名主体进行授权，而授权失败所抛出的异常
     */
    @ExceptionHandler(UnauthenticatedException.class)
    public Result handle401(UnauthenticatedException e) {
        return Result.fail(401, "无权访问(Unauthorized):当前Subject是匿名Subject，请先登录");
    }


    /**
     * 捕捉其他所有异常
     */
    @ExceptionHandler(Exception.class)
    public Result globalException(HttpServletRequest request, Throwable ex) {
        return Result.fail(500, ex.toString() + ": " + ex.getMessage());
    }


    //运行时错误
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
//    @ExceptionHandler(RuntimeException.class)
//    public Result handle(RuntimeException e){
//        return Result.fail(403,"运行时的错误"+e.getMessage());
//    }


    @ExceptionHandler(TokenExpiredException.class)
    public Result handler(TokenExpiredException e){
        return Result.fail(400,"token已经过期了，请重新登录"+e.getMessage());
    }


}
